//
//  ComposedViewController.swift
//  JLWeibo
//
//  Created by sunjinliang on 15/12/16.
//  Copyright © 2015年 sunjinliang. All rights reserved.
//

import UIKit
import SVProgressHUD
class ComposedViewController: UIViewController,UITextViewDelegate{
   lazy var picturePickerController = PicturePickerController()
    override func viewDidLoad() {
        super.viewDidLoad()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardValueChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    @objc private func keyboardValueChange(noti: NSNotification){

        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue
        let rect = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as? NSValue )?.CGRectValue()
        let curve = (noti.userInfo![UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.integerValue
        let offSet = -UIScreen.mainScreen().bounds.height + (rect?.origin.y)!
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offSet)
        }
        UIView.animateWithDuration(duration!) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve!)!)
            self.view.layoutIfNeeded()
        }
    }
    
    override func loadView() {
        view = UIView()
        setupUI()
    }
    override func viewDidAppear(animated: Bool) {
        if picturePickerController.view.bounds.height == 0{
            textView.becomeFirstResponder()
        }
    }
   @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
        textView.resignFirstResponder()
    }
   @objc private func sendStatus(){
    let status = textView.emoticonText
    SVProgressHUD.show()
    NetworkTools.onceToken.sendStatus(status, image:picturePickerController.pictures.last) { (result, error) -> () in
        if error != nil {
            print(error)
            SVProgressHUD.showInfoWithStatus("上帝,您的网络不给力")
            SVProgressHUD.dismiss()
            return
        }
        SVProgressHUD.showInfoWithStatus("上帝,您的发布成功")
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))),  dispatch_get_main_queue(), { () -> Void in
            SVProgressHUD.dismiss()
            
            self.close()
        })
        
     }
    }
    
    private lazy var textView: UITextView = {
       let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18)
        tv.keyboardDismissMode = .OnDrag
        tv.delegate = self
        tv.alwaysBounceVertical = true
        return tv
    }()
    private lazy var placeHoderLabel = UILabel(text1: "分享新鲜事........", color: UIColor.lightGrayColor(), fontSize: 18)
    //工具栏
    
    private lazy var toolBar = UIToolbar()
    private lazy var emoticonView : EmoticonView = EmoticonView { (emoticon) -> () in
        self.textView.insertEmoticon(emoticon)
    }
    func selectEmoticon(){
        textView.resignFirstResponder()
        if textView.inputView == nil{
            textView.inputView = emoticonView
        }else{
            textView.inputView = nil
        }
        textView.becomeFirstResponder()
    }
  @objc private  func selectPicture(){
       textView.resignFirstResponder()
    if picturePickerController.view.bounds.height > 0{
        return
    }
    picturePickerController.view.snp_updateConstraints { (make) -> Void in
        make.height.equalTo(view.bounds.height * 0.6)
    }
    textView.snp_remakeConstraints { (make) -> Void in
        make.top.equalTo(self.snp_topLayoutGuideBottom)
        make.left.equalTo(view.snp_left)
        make.right.equalTo(view.snp_right)
        make.bottom.equalTo(picturePickerController.view.snp_top)
    }
    }
    func setupUI(){
        automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = UIColor.whiteColor()
        prepareNavigationBar()
        preparetoolBar()
        prepareTextView()
        preparePicturesPicker()
        }
    private func preparePicturesPicker(){
        addChildViewController(picturePickerController)
        view.insertSubview(picturePickerController.view, belowSubview: toolBar)
    
        picturePickerController.view.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(0)
            make.bottom.equalTo(view.snp_bottom)
        }
        
    }
    private func prepareTextView(){
        view.addSubview(textView)
        textView.addSubview(placeHoderLabel)
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolBar.snp_top)
        }
        placeHoderLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(textView.snp_left).offset(5)
            make.top.equalTo(textView.snp_top).offset(8)
            
        }
    }
    private func preparetoolBar(){
        view.addSubview(toolBar)
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(44)
            make.bottom.equalTo(view.snp_bottom)
        }
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName":"selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        var items = [UIBarButtonItem]()
        for dict  in itemSettings{
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, action: dict["actionName"]))
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
        
    }
        //准备导航栏
    private func prepareNavigationBar(){
            navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
            navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
             navigationItem.rightBarButtonItem?.enabled = false
            let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
            let sendLabel = UILabel(text1: "发布微博", fontSize: 15)
            let nameLabel = UILabel(text1: UserAccountVM.shareUserAccount.Account!.screen_name!, color: UIColor.lightGrayColor(), fontSize: 12)
            titleView.addSubview(sendLabel)
            titleView.addSubview(nameLabel)
            sendLabel.snp_makeConstraints { (make) -> Void in
                make.centerX.equalTo(titleView.snp_centerX)
                make.top.equalTo(titleView.snp_top)
            }
            nameLabel.snp_makeConstraints { (make) -> Void in
                make.centerX.equalTo(titleView.snp_centerX)
                make.bottom.equalTo(titleView.snp_bottom)
                navigationItem.titleView = titleView

        }
    }
}
///textView的代理方法
extension ComposedViewController{
    func textViewDidChange(textView: UITextView) {
        placeHoderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}